"""
ProjectName:qq_tools_bot 
FileName:morning_paper.py 
IdeaName:PyCharm 
UserName:zhao
UserMail:2909552840@qq.com
UserHomepage:https://www.zywi.cn
CreationTime:2024/11/2 上午9:52  
"""
from api import MessageApi
from models import MessageReport, MessageType, Message, MsType, MsData
from utils import print_red


class MorningPaper:
    """
    早报
    """

    def __init__(self, message_report: MessageReport, message_api: MessageApi):
        """
        初始化函数
        :param message_report: 消息上报
        :param message_api: 消息API
        """
        super().__init__()
        self.message_report = message_report
        self.message_api = message_api
        self.start()

    def start(self) -> None:
        """
        启动函数
        :return:
        """
        raw_message = self.message_report.raw_message
        if raw_message != '早报':
            return

        message_type = self.message_report.message_type
        group_id = self.message_report.group_id
        user_id = self.message_report.user_id
        ms_list = []

        # 准备图像消息
        ms_img = Message()
        ms_img.type = MsType.IMAGE
        ms_img.data = MsData(url='https://api.03c3.cn/api/zb')

        try:
            if message_type == MessageType.GROUP:
                # 群聊消息
                ms_at = Message()
                ms_at.type = MsType.AT
                ms_at.data = MsData(qq=user_id)
                ms_list.append(ms_at)
                ms_list.append(ms_img)
                self.message_api.send_group_msg(group_id, ms_list)
            elif message_type == MessageType.PRIVATE:
                # 私聊消息
                self.message_api.send_private_msg(user_id, [ms_img])
        except Exception as e:
            print_red('MorningPaperError:', e)
            self.handle_error(message_type, user_id, group_id)

    def handle_error(self, message_type, user_id, group_id):
        """
        处理错误消息。
        """
        error_message = Message()
        error_message.type = MsType.TEXT
        error_message.data = MsData(url='早报生成失败')

        if message_type == MessageType.GROUP:
            ms_list = [Message(type=MsType.AT, data=MsData(qq=user_id)), error_message]
            self.message_api.send_group_msg(group_id, ms_list)
        elif message_type == MessageType.PRIVATE:
            self.message_api.send_private_msg(user_id, [error_message])
